import java.sql.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

public class Client {

    public static void main(String[] args) {
        new Login();
    }
}

class ClientReadAndPrint extends Thread {
    static Socket mySocket = null;
    static JTextField textInput;
    static JTextArea textShow;
    static JFrame chatViewJFrame;
    static BufferedReader in = null;
    static PrintWriter out = null;
    static String userName;

    public void run() {
        try {
            in = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
            while (true) {
                String str = in.readLine();
                textShow.append(str + '\n');
                textShow.setCaretPosition(textShow.getDocument().getLength());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class LoginListen implements ActionListener {
        JTextField textField;
        JPasswordField pwdField;
        JFrame loginJFrame;
        ChatView chatView = null;
        public void setJTextField(JTextField textField) {
            this.textField = textField;
        }
        public void setJPasswordField(JPasswordField pwdField) {
            this.pwdField = pwdField;
        }
        public void setJFrame(JFrame jFrame) {
            this.loginJFrame = jFrame;
        }
        public void actionPerformed(ActionEvent event) {
            userName = textField.getText();
            String userPwd = String.valueOf(pwdField.getPassword());

            if (validateUser(userName, userPwd)) {
                chatView = new ChatView(userName);
                try {
                    InetAddress addr = InetAddress.getByName(null);
                    mySocket = new Socket(addr, 8081);
                    loginJFrame.setVisible(false);
                    out = new PrintWriter(mySocket.getOutputStream());
                    out.println("用户【" + userName + "】进入聊天室！");
                    out.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ClientReadAndPrint readAndPrint = new ClientReadAndPrint();
                readAndPrint.start();
                ClientFileThread fileThread = new ClientFileThread(userName, chatViewJFrame, out);
                fileThread.start();
            } else {
                JOptionPane.showMessageDialog(loginJFrame, "账号或密码错误，请重新输入！", "提示", JOptionPane.WARNING_MESSAGE);
            }
        }

        private boolean validateUser(String userName, String userPwd) {
            boolean isValid = false;
            Connection conn = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;

            try {
                String url = "jdbc:mysql://localhost:3306/userinfo?serverTimezone=Asia/Shanghai";
                // 连接数据库 (请根据你的数据库配置进行修改)
                conn = DriverManager.getConnection(url, "root", "123456");

                String sql = "SELECT * FROM user_info WHERE username = ? AND password = ?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, userName);
                pstmt.setString(2, userPwd);
                rs = pstmt.executeQuery();
                if (rs.next()) {
                    isValid = true;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (rs != null) rs.close();
                    if (pstmt != null) pstmt.close();
                    if (conn != null) conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return isValid;
        }
    }

    class ChatViewListen implements ActionListener {
        public void setJTextField(JTextField text) {
            textInput = text;
        }

        public void setJTextArea(JTextArea textArea) {
            textShow = textArea;
        }

        public void setChatViewJf(JFrame jFrame) {
            chatViewJFrame = jFrame;
            chatViewJFrame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    out.println("用户【" + userName + "】离开聊天室！");
                    out.flush();
                    System.exit(0);
                }
            });
        }

        public void actionPerformed(ActionEvent event) {
            try {
                String str = textInput.getText();
                if ("".equals(str)) {
                    textInput.grabFocus();
                    JOptionPane.showMessageDialog(chatViewJFrame, "输入为空，请重新输入！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                out.println(userName + "说：" + str);
                out.flush();

                textInput.setText("");
                textInput.grabFocus();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
